{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 原文地址 [blog.csdn.net](https://blog.csdn.net/qq\\_32188669/article/details/107966322)\n",
    "\n",
    "python 给内存和 cpu 使用量设置限制\n",
    "=======================\n",
    "\n",
    "在 linux 系统中，使用 Python 对内存和 cpu 使用量设置限制需要通过 resource 模块来完成。resource 文档地址：[resource — Resource usage information](https://docs.python.org/zh-cn/3/library/resource.html)\n",
    "\n",
    "限制 Python 进程 cpu 使用时间的样例如下：\n",
    "\n",
    "```py\n",
    "import signal\n",
    "import resource\n",
    "import os\n",
    "\n",
    "def time_exceeded(signo, frame):\n",
    "    print(\"time's up\")\n",
    "    raise SystemExit(1)\n",
    "def set_max_runtime(seconds):\n",
    "    soft,hard = resource.getrlimit(resource.RLIMIT_CPU)\n",
    "    resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard))\n",
    "    signal.signal(signal.SIGXCPU, time_exceeded)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    set_max_runtime(5)\n",
    "    while True:\n",
    "        pass\n",
    "\n",
    "```\n",
    "\n",
    "运行上述代码，当超时时会产生 SIGXCPU 信号。程序就会做清理工作然后退出。  \n",
    "要限制内存的使用可以使用如下函数：\n",
    "\n",
    "```py\n",
    "def limit_memory(maxsize):\n",
    "    soft, hard = resource.getrlimit(resource.RLIMIT_AS)\n",
    "    resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))\n",
    "\n",
    "```\n",
    "\n",
    "当设定了内存限制后，如果没有更多的内存可用，程序就会开始产生 MemoryError 异常。\n",
    "\n",
    "注：以上示例代码来源于：《Python Cookbook》P575 “给内存和 cpu 使用量设置限制”。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
